package com.zmn.oms.dubbo.impl.zmn.serviceprovider.order;

import org.apache.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.validator.ValidateResult;
import com.zmn.common.utils.validator.ValidatorUtil;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.OrderPartPostDRO;
import com.zmn.oms.dubbo.dto.zmn.order.serviceprovider.OrderPartPostListDIO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.serviceprovider.order.OrderPartsPostRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.dto.part.OrderPartPostListDTO;
import com.zmn.oms.model.entity.fcorderpart.FcOrderPartQuery;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPart;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPartPost;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPartPostQuery;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartPostService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartService;
import com.zmn.oms.zmn.business.interfaces.part.ZsOrderFactoryPartBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：服务商  订单操作-邮寄旧件
 *
 * @author yule
 * @date 2019/05/16 16:05
 */
@Deprecated
@Service(loadbalance = "roundrobin", timeout = 5000, retries = 2, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class OrderPartsPostRemoteServiceImpl extends OrderBaseRemoteService implements OrderPartsPostRemoteService {

	private static final String TAG = "服务商 -邮寄旧件";
	private Logger logger = LoggerFactory.getLogger(OrderPartsPostRemoteServiceImpl.class);

	@Autowired
	private OrderFactoryPartService orderFactoryPartService;
	@Autowired
	private ZsOrderFactoryPartBService zsOrderFactoryPartBService;
	@Autowired
	private OrderFactoryPartPostService orderFactoryPartPostService;

	@Override
	public ResponseDTO<OrderPartPostDRO> partsPost(Long orderId, Long workId) {
		logger.info("[{}] 邮寄旧件：{}", TAG, "orderId:" + orderId, "workId:" + workId);

		Objects.requireNonNull(orderId);
		try {
			//1.是否返厂是   2.审核状态：成功  3.旧件邮寄返厂：（2）
			FcOrderPartQuery query = new FcOrderPartQuery();
			query.setReviewStatus(OrderConsts.ORDER_MEMBER_REVIEW_RESULT_SUCCESS);//审核状态：成功
			query.setRetrieve(OrderConsts.FACTORY_PART_POST_TYPE_RETURN);//是旧件返厂
			query.setOrderId(orderId);
			List<OrderFactoryPart> partsList = orderFactoryPartService.listByQuery(query);

			logger.info("[{}] 配件信息partsList：{}", TAG, partsList);

			if (partsList == null || partsList.isEmpty()) {
				throw new OmsBaseException("没有需要的邮寄旧件信息。");
			}

			List<Integer> fcOrderPartIdList = Lists.newArrayList();
			partsList.forEach(e -> fcOrderPartIdList.add(e.getFcOrderPartId()));

			OrderFactoryPartPostQuery postQuery = new OrderFactoryPartPostQuery();
			postQuery.setFcOrderPartIdList(fcOrderPartIdList);
			postQuery.setOrderId(orderId);
			postQuery.setFcOrderPartPostType(OrderConsts.FACTORY_PART_POST_TYPE_RETURN);// 旧件邮寄返厂

			List<OrderFactoryPartPost> partPostList = orderFactoryPartPostService.listByQuery(postQuery);

			logger.info("[{}] 快件物流信息partPostList：{}", TAG, partPostList);

			List<OrderPartPostDRO> partPostDRO = BeanMapper.mapList(partPostList, OrderPartPostDRO.class);

			partPostDRO.forEach(partPost -> {
				Optional<OrderFactoryPart> postOpt = partsList.stream().filter(item -> Objects.equals(item.getFcOrderPartId(), partPost.getFcOrderPartId())).findFirst();
				if (postOpt.isPresent()) {
					OrderFactoryPart post = postOpt.get();
					partPost.setSrc(post.getSrc());
					partPost.setPartName(post.getPartName());
					partPost.setPartFullName(post.getPartFullName());
					partPost.setCategName(post.getCategName());
					partPost.setCategOneName(post.getCategOneName());
					partPost.setNumber(post.getNumber());
					partPost.setUnit(post.getUnit());
				}
			});

			return ResponseUtil.responseSuccess(partPostDRO, "OK");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 查询错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}

	}

	@Override
	public ResponseDTO savePartsPost(OrderPartPostListDIO partPostListDIO) {
		logger.info("[{}] 保存邮寄旧件：{}", TAG, partPostListDIO);

		ValidateResult validateResult = ValidatorUtil.validator(partPostListDIO);

		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
		}

		try {
			OrderPartPostListDTO  orderPartPost= BeanMapper.map(partPostListDIO, OrderPartPostListDTO.class);
			orderPartPost.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SERVICEPROVIDER);
			orderPartPost.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SERVICEPROVIDER) + "-" + partPostListDIO.getOperator());
			zsOrderFactoryPartBService.updateOldPostFcPart(orderPartPost);

			return ResponseUtil.responseSuccess("OK");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 保存邮寄旧件错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}
	}

	@Override
	public ResponseDTO partsPostPermiss(Long orderId) {
		int num = orderFactoryPartPostService.findOldPartPostCount(orderId);
		return ResponseUtil.responseSuccess(num, "OK");

	}

}
